/**
 * @Date: Mar 8, 2010 8:07:06 PM
 */
package com.philip.journal.home.controller.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;

import com.philip.journal.core.Constant;
import com.philip.journal.core.controller.ResponseHandler;
import com.philip.journal.core.exception.JournalException;
import com.philip.journal.core.service.ServiceProxy;
import com.philip.journal.home.service.util.BeanToMapConverter;

/**
 * @author cry30
 */
public class GetPreferenceAction extends AbstractTreeAction {

    /**
     * Default delegate constructor.
     *
     * @param serviceProxy Service proxy to be injected by Spring.
     * @param responseHandler Response handler to be injected by Spring.
     */
    public GetPreferenceAction(final ServiceProxy serviceProxy, final ResponseHandler responseHandler) {
        super(serviceProxy, responseHandler);
    }

    @Override
    public void execute() throws ServletException, IOException {
        try {

            final String nodeId = getHttpServletRequest().getParameter(NODE_ID);
            if ("b-0".equals(nodeId)) {
                final List<Map<String, Object>> preferences = getServiceProxy().getPreferences();
                final BeanToMapConverter mapConverter = getResponseHandler().getConverterFactoryMap().get(
                        Constant.BeanConverter.CFGITEM_TO_JSON);
                for (final Map<String, Object> map : preferences) {
                    map.put("leaf", true);
                }
                getResponseHandler().respondList(getHttpServletResponse(), preferences, mapConverter);
            } else {
                getResponseHandler().respondList(getHttpServletResponse(), new ArrayList<String>(), null);
            }
        } catch (final JournalException e) {
            getLogger().debug(e.getMessage(), e);
            getResponseHandler().respondFail(getHttpServletResponse(), e.getMessage());
        }
    }
}
